<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Retrofit</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="A type-safe REST client for Android and Java">
    <link href="static/bootstrap-combined.min.css" rel="stylesheet">
    <link href="static/app.css" rel="stylesheet">
    <link href="static/app-theme.css" rel="stylesheet">
    <link href="http://fonts.googleapis.com/css?family=Roboto:400,300italic,100,100italic,300" rel="stylesheet" type="text/css">
    <!--[if lt IE 9]><script src="static/html5shiv.min.js"></script><![endif]-->
  </head>
  <body data-target=".content-nav">
    <header>
      <div class="container">
        <div class="row">
          <div class="span5">
            <h1>Retrofit</h1>
          </div>
          <div class="span7">
            <menu>
              <ul>
                <li><a href="#download" class="menu download">Download <span class="version-tag">Latest</span></a></li>
                <li><a href="http://github.com/square/retrofit" data-title="View GitHub Project" class="menu github"><img src="static/icon-github.png" alt="GitHub"/></a></li>
                <li><a href="http://square.github.io/" data-title="Square Open Source Portal" class="menu square"><img src="static/icon-square.png" alt="Square"/></a></li>
              </ul>
            </menu>
          </div>
      </div>
    </header>
    <section id="subtitle">
      <div class="container">
        <div class="row">
          <div class="span12">
            <h2>A type-safe <strong>REST client</strong> for Android and Java</h2>
          </div>
        </div>
      </div>
    </section>
    <section id="body">
      <div class="container">
        <div class="row">
          <div class="span9">
            <h3 id="introduction">Introduction</h3>
            <p>Retrofit turns your REST API into a Java interface.</p>
            <pre class="prettyprint">public interface GitHubService {
  @GET("/users/{user}/repos")
  List&lt;Repo> listRepos(@Path("user") String user);
}</pre>
            <p>The <code>RestAdapter</code> class generates an implementation of the <code>GitHubService</code> interface.</p>
            <pre class="prettyprint">RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .build();

GitHubService service = restAdapter.create(GitHubService.class);</pre>
            <p>Each call on the generated <code>GitHubService</code> makes an HTTP request to the remote webserver.</p>
            <pre class="prettyprint">List&lt;Repo> repos = service.listRepos("octocat");</pre>
            <p>Use annotations to describe the HTTP request:</p>
            <ul>
              <li>URL parameter replacement and query parameter support</li>
              <li>Object conversion to request body (e.g., JSON, protocol buffers)</li>
              <li>Multipart request body and file upload</li>
            </ul>

            <h3 id="api-declaration">API Declaration</h3>
            <p>Annotations on the interface methods and its parameters indicate how a request will be handled.</p>

            <h4>Request Method</h4>
            <p>Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: <code>GET</code>, <code>POST</code>, <code>PUT</code>, <code>DELETE</code>, and <code>HEAD</code>. The relative URL of the resource is specified in the annotation.</p>
            <pre class="prettyprint">@GET("/users/list")</pre>
            <p>You can also specify query parameters in the URL.</p>
            <pre class="prettyprint">@GET("/users/list?sort=desc")</pre>
            </pre>

            <h4>URL Manipulation</h4>
            <p>A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by <code>{</code> and <code>}</code>. A corresponding parameter must be annotated with <code>@Path</code> using the same string.</p>
            <pre class="prettyprint">@GET("/group/{id}/users")
List&lt;User> groupList(@Path("id") int groupId);</pre>
            <p>Query parameters can also be added.</p>
            <pre class="prettyprint">@GET("/group/{id}/users")
List&lt;User> groupList(@Path("id") int groupId, @Query("sort") String sort);</pre>
            <p>For complex query parameter combinations a <code>Map</code> can be used.</p>
            <pre class="prettyprint">@GET("/group/{id}/users")
List&lt;User> groupList(@Path("id") int groupId, @QueryMap Map&lt;String, String&gt; options);</pre>

            <h4>Request Body</h4>
            <p>An object can be specified for use as an HTTP request body with the <code>@Body</code> annotation.</p>
            <pre class="prettyprint">@POST("/users/new")
void createUser(@Body User user, Callback&lt;User> cb);</pre>
            <p>The object will also be converted using the <code>RestAdapter</code>'s converter.</p>

            <h4>Form Encoded and Multipart</h4>
            <p>Methods can also be declared to send form-encoded and multipart data.</p>
            <p>Form-encoded data is sent when <code>@FormUrlEncoded</code> is present on the method. Each key-value pair is annotated with <code>@Field</code> containing the name and the object providing the value.</p>
            <pre class="prettyprint">@FormUrlEncoded
@POST("/user/edit")
User updateUser(@Field("first_name") String first, @Field("last_name") String last);</pre>
            <p>Multipart requests are used when <code>@Multipart</code> is present on the method. Parts are declared using the <code>@Part</code> annotation.</p>
            <pre class="prettyprint">@Multipart
@PUT("/user/photo")
User updateUser(@Part("photo") TypedFile photo, @Part("description") TypedString description);</pre>
            <p>Multipart parts use the <code>RestAdapter</code>'s converter or they can implement <code>TypedOutput</code> to handle their own serialization.</p>

            <h4>Header Manipulation</h4>
            <p>You can set static headers for a method using the <code>@Headers</code> annotation.</p>
            <pre class="prettyprint">@Headers("Cache-Control: max-age=640000")
@GET("/widget/list")
List&lt;Widget> widgetList();</pre>
            <pre class="prettyprint">@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("/users/{username}")
User getUser(@Path("username") String username);</pre>
            <p>Note that headers do not overwrite each other. All headers with the same name will be included in the request.</p>
            <p>A request Header can be updated dynamically using the <code>@Header</code> annotation. A corresponding parameter must be provided to the <code>@Header</code>. If the value is null, the header will be omitted. Otherwise, <code>toString</code> will be called on the value, and the result used.</p>
            <pre class="prettyprint">@GET("/user")
void getUser(@Header("Authorization") String authorization, Callback&lt;User> callback)</pre>
            <p>Headers that need to be added to every request can be specified using a <code>RequestInterceptor</code>. The following code creates a <code>RequestInterceptor</code> that will add a <code>User-Agent</code> header to every request.</p>
            <pre class="prettyprint">RequestInterceptor requestInterceptor = new RequestInterceptor() {
  @Override
  public void intercept(RequestFacade request) {
    request.addHeader("User-Agent", "Retrofit-Sample-App");
  }
};

RestAdapter restAdapter = new RestAdapter.Builder()
  .setEndpoint("https://api.github.com")
  .setRequestInterceptor(requestInterceptor)
  .build();</pre>

            <h4>Synchronous vs. Asynchronous vs. Observable</h4>
            <p>Methods can be declared for either synchronous or asynchronous execution.</p>
            <p>A method with a return type will be executed synchronously.</p>
            <pre class="prettyprint">@GET("/user/{id}/photo")
Photo getUserPhoto(@Path("id") int id);</pre>
            <p>Asynchronous execution requires the last parameter of the method be a <code>Callback</code>.</p>
            <pre class="prettyprint">@GET("/user/{id}/photo")
void getUserPhoto(@Path("id") int id, Callback&lt;Photo> cb);</pre>
            <p>On Android, callbacks will be executed on the main thread. For desktop applications callbacks will happen on the same thread that executed the HTTP request.</p>

            <p>Retrofit also integrates <a href="https://github.com/Netflix/RxJava/wiki">RxJava</a> to support methods with a return type of <code>rx.Observable</code></p>
            <pre class="prettyprint">@GET("/user/{id}/photo")
Observable&lt;Photo> getUserPhoto(@Path("id") int id);</pre>
            <p>Observable requests are subscribed asynchronously and observed on the same thread that executed the HTTP request.  To observe on a different thread (e.g. Android's main thread) call <code>observeOn(Scheduler)</code> on the returned <code>Observable</code>.</p>

            <h4>Response Object Type</h4>
            <p>HTTP responses are automatically converted to a specified type using the <code>RestAdapter</code>'s converter which defaults to JSON. The desired type is declared as the method return type or using the <code>Callback</code> or <code>Observable</code>.
            <pre class="prettyprint">@GET("/users/list")
List&lt;User> userList();

@GET("/users/list")
void userList(Callback&lt;List&lt;User>> cb);

@GET("/users/list")
Observable&lt;List&lt;User>> userList();</pre>
            <p>For access to the raw HTTP response use the <code>Response</code> type.</p>
            <pre class="prettyprint">@GET("/users/list")
Response userList();

@GET("/users/list")
void userList(Callback&lt;Response> cb);

@GET("/users/list")
Observable&lt;Response> userList();</pre>

            <h3 id="restadapter-configuration">RestAdapter Configuration</h3>
            <p><code>RestAdapter</code> is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.</p>

            <h4>JSON Conversion</h4>
            <p>Retrofit uses <a href="https://code.google.com/p/google-gson/">Gson</a> by default to convert HTTP bodies to and from JSON. If you want to specify behavior that is different from Gson's defaults (e.g. naming policies, date formats, custom types), provide a new <code>Gson</code> instance with your desired behavior when building a <code>RestAdapter</code>. Refer to the <a href="https://sites.google.com/site/gson/gson-user-guide">Gson documentation</a> for more details on customization.</p>
            <h4>Custom Gson Converter Example</h4>
            <p>The following code creates a new <code>Gson</code> instance that will convert all fields from lower case with underscores to camel case and vice versa. It also registers a type adapter for the <code>Date</code> class. This <code>DateTypeAdapter</code> will be used anytime Gson encounters a <code>Date</code> field.</p>
            <p>The <code>gson</code> instance is passed as a parameter to <code>GsonConverter</code>, which is a wrapper class for converting types.</p>
            <pre class="prettyprint">Gson gson = new GsonBuilder()
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
    .registerTypeAdapter(Date.class, new DateTypeAdapter())
    .create();

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .setConverter(new GsonConverter(gson))
    .build();

GitHubService service = restAdapter.create(GitHubService.class);</pre>
            <p>Each call on the generated <code>GithubService</code> will return objects converted using the Gson implementation provided to the <code>RestAdapter</code>.</p>
            <h4>Content format Agnostic</h4>
            <p>In addition to JSON, Retrofit can be configured to use other content formats. Retrofit provides alternate converters for XML (using <a href="http://simple.sourceforge.net/">Simple</a>) and Protocol Buffers (using <a href="https://code.google.com/p/protobuf/">protobuf</a> or <a href="https://github.com/square/wire">Wire</a>). Please see the <a href="https://github.com/square/retrofit/tree/master/retrofit-converters">retrofit-converters</a> directory for the full listing of converters.</p>
            <p>The following code shows how to use <code>SimpleXMLConverter</code> to communicate with an API that uses XML</p>
            <pre class="prettyprint">RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.soundcloud.com")
    .setConverter(new SimpleXMLConverter())
    .build();

SoundCloudService service = restAdapter.create(SoundCloudService.class);</pre>
            <h4>Custom Converters</h4>
            <p>If you need to communicate with an API that uses a content-format that Retrofit does not support out of the box (e.g. YAML, txt, custom format) or you wish to use a different library to implement an existing format, you can easily create your own converter. Create a class that implements the <a href="https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit/converter/Converter.java"><code>Converter</code> interface</a> and pass in an instance when building your adapter.</p>
            <h4>Custom Error Handling</h4>
            <p>If you need custom error handling for requests, you may provide your own <code>ErrorHandler</code>. The following code shows how to throw a custom exception when a response returns a HTTP 401 status code</p>
            <pre class="prettyprint">
class MyErrorHandler implements ErrorHandler {
  @Override public Throwable handleError(RetrofitError cause) {
    Response r = cause.getResponse();
    if (r != null && r.getStatus() == 401) {
      return new UnauthorizedException(cause);
    }
    return cause;
  }
}

RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint("https://api.github.com")
    .setErrorHandler(new MyErrorHandler())
    .build();</pre>
            <p>Note that if the return exception is checked, it must be declared on the interface method. It is recommended that you pass the supplied <code>RetrofitError</code> as the cause to any new exceptions you throw.</p>

            <h4>Logging</h4>
            <p>If you need to take a closer look at the requests and responses you can easily add logging levels to the <code>RestAdapter</code> with the <code>LogLevel</code> property. The possible logging levels are <code>BASIC</code>, <code>FULL</code>, <code>HEADERS</code>, and <code>NONE</code>.</p>
            <p>The following code shows the addition of a full log level which will log the headers, body, and metadata for both requests and responses.</p>
            <pre class="prettyprint">
RestAdapter restAdapter = new RestAdapter.Builder()
    .setLogLevel(RestAdapter.LogLevel.FULL)
    .setEndpoint("https://api.github.com")
    .build();</pre>
            <p>This logging can be added or changed at any point in the <code>RestAdapter</code>'s lifecycle by calling the same <code>.setLogLevel()</code> method and supplying a different <code>LogLevel</code> value.</p>

            <h3 id="download">Download</h3>
            <p><a href="http://repository.sonatype.org/service/local/artifact/maven/redirect?r=central-proxy&g=com.squareup.retrofit&a=retrofit&v=LATEST" class="dl version-href">&darr; <span class="version-tag">Latest</span> JAR</a></p>
            <p>The source code to the Retrofit, its samples, and this website is <a href="http://github.com/square/retrofit">available on GitHub</a>.</p>
            <h4>Maven</h4>
            <pre class="prettyprint">&lt;dependency>
  &lt;groupId>com.squareup.retrofit&lt;/groupId>
  &lt;artifactId>retrofit&lt;/artifactId>
  &lt;version><span class="version pln"><em>(insert latest version)</em></span>&lt;/version>
&lt;/dependency></pre>
            <h4>Gradle</h4>
            <pre class="prettyprint">
compile 'com.squareup.retrofit:retrofit:<span class="version pln"><em>(insert latest version)</em></span>'
</pre>
<h4>Integration with OkHttp</h4>
            <p>When using Retrofit together with OkHttp, OkHttp (version 1.6.0 or newer) and OkHttp-UrlConnection are now required.</p>
            <h4>Maven</h4>
            <pre class="prettyprint">&lt;dependency>
  &lt;groupId>com.squareup.okhttp&lt;/groupId>
  &lt;artifactId>okhttp&lt;/artifactId>
  &lt;version>2.0.0&lt;/version>
&lt;/dependency>
&lt;dependency>
  &lt;groupId>com.squareup.okhttp&lt;/groupId>
  &lt;artifactId>okhttp-urlconnection&lt;/artifactId>
  &lt;version>2.0.0&lt;/version>
&lt;/dependency>
</pre>
            <h4>Gradle</h4>
<pre class="prettyprint">
compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
compile 'com.squareup.okhttp:okhttp:2.0.0'
</pre>
            <h3 id="contributing">Contributing</h3>
            <p>If you would like to contribute code you can do so through GitHub by forking the repository and sending a pull request.</p>
            <p>When submitting code, please make every effort to follow existing conventions and style in order to keep the code as readable as possible. Please also make sure your code compiles by running <code>mvn clean verify</code>.</p>
            <p>Before your code can be accepted into the project you must also sign the <a href="http://squ.re/sign-the-cla">Individual Contributor License Agreement (CLA)</a>.</p>

            <h3 id="license">License</h3>
            <pre>Copyright 2013 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.</pre>
          </div>
          <div class="span3">
            <div class="content-nav" data-spy="affix" data-offset-top="80">
              <ul class="nav nav-tabs nav-stacked primary">
                <li><a href="#introduction">Introduction</a></li>
                <li><a href="#api-declaration">API Declaration</a></li>
                <li><a href="#restadapter-configuration">RestAdapter Configuration</a></li>
                <li><a href="#download">Download</a></li>
                <li><a href="#contributing">Contributing</a></li>
                <li><a href="#license">License</a></li>
              </ul>
              <ul class="nav nav-pills nav-stacked secondary">
                <li><a href="javadoc/index.html">Javadoc</a></li>
                <li><a href="http://stackoverflow.com/questions/tagged/retrofit?sort=active">StackOverflow</a></li>
              </ul>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="span12 logo">
            <a href="https://squareup.com"><img src="static/logo-square.png" alt="Square, Inc."/></a>
          </div>
        </div>
      </div>
    </section>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="static/bootstrap.min.js"></script>
    <script src="static/jquery.smooth-scroll.min.js"></script>
    <script src="static/jquery-maven-artifact.min.js"></script>
    <script src="static/prettify.js"></script>
    <script type="text/javascript">
      $(function() {
        // Syntax highlight code blocks.
        prettyPrint();

        // Spy on scroll position for real-time updating of current section.
        $('body').scrollspy();

        // Use smooth-scroll for internal links.
        $('a').smoothScroll();

        // Enable tooltips on the header nav image items.
        $('.menu').tooltip({
          placement: 'bottom',
          trigger: 'hover',
          container: 'body',
          delay: {
            show: 500,
            hide: 0
          }
        });

        // Look up the latest version of the library.
        $.fn.artifactVersion('com.squareup.retrofit', 'retrofit', function(version, url) {
          $('.version').text(version);
          $('.version-tag').text('v' + version);
          $('.version-href').attr('href', url);
        });
      });

      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-40704740-4', 'github.io');
      ga('send', 'pageview');
    </script>
  </body>
</html>
